import { createSlice } from "@reduxjs/toolkit";
import { getFindByParentId } from "@/api/dict";
import { useSelector } from "react-redux";
import {upload} from "@testing-library/user-event/dist/upload";

const findInfo: any = (arr: any, id: number) => {
    let info;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
            info = arr[i];
        } else if (arr[i].children && arr[i].children.length > 0) {
            info = findInfo(arr[i].children, id);
        }
        if (info) {
            break;
        }
    }
    return info;
}

const dictSlice = createSlice({
    name: "dict",
    initialState: {
        dictList: [],
        // 1- 增加loading状态
        loading:false
    },
    /*思路：
   * 1- 根据省份ID,可以获得省份下的类别
   * 2- 获取到省份下的类别后，需要将数据作为省份对象下的children属性值
   * */
    reducers: {
        // 2- 增加修改loading方法
        upLoading(state,{ payload}){
            state.loading = payload;
        },
        upDictList(state, { payload }) {
            // payload.parentId 作为条件，找省份
            // console.log(payload);
            // const info: any = state.dictList.find((v: any) => v.id === payload.parentId);
            const info: any = findInfo(state.dictList, payload.parentId);
            if (info) {
                info.children = payload.dictList;
            } else {
                state.dictList = payload.dictList;
            }
        }
    }
})

const { upDictList ,upLoading} = dictSlice.actions;
export const getFindByParentIdAsync = (parentId: number) => {
    return async (dispatch: any) => {
        dispatch(upLoading(true));
        const result = await getFindByParentId(parentId);
        
        // dispatch(upDictList({
        //     dictList: result.data.map((item: any) => {
        //         if (item.hasChildren) {
        //             item.children = [];
        //         }
        //         return item;
        //     }),
        //     parentId
        // }));
        dispatch(upLoading(false));
    }
}
export const useSelectorDict = () => useSelector((state: any) => state.dict);
export default dictSlice.reducer;